package com.vanzo.ui;

import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.vanzo.adapter.BindNFCAdapter;
import com.vanzo.encryption.Encryption;
import com.vanzo.encryption.R;
import com.vanzo.nfc.NFCManager;
import com.vanzo.talkie.Follower;
import com.vanzo.util.LogUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by tisen on 2018/3/8.
 */

public class NFCBindActivity extends BaseActivity {

    private RecyclerView recyclerView;
    private Button bind;
    private PopupWindow bottomPop;

    private NFCManager nfcManager;
    private BindNFCAdapter adapter;

    private List<Follower> followers;
    private Follower bindingOne;
    private byte[] gk;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfc_bind);
        recyclerView = (RecyclerView) findViewById(R.id.bind_recycler);
        bind = (Button) findViewById(R.id.start_bind);
        bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startBind();
                bind.setVisibility(View.INVISIBLE);
            }
        });
        followers = initFollowers();
    }

    private List<Follower> initFollowers() {
        return new ArrayList<>();
    }


    @Override
    protected void onStart() {
        LogUtil.put(this,"onStart",LogUtil.WARN);
        super.onStart();
        gk = Encryption.getGroupKey();
        nfcManager = new NFCManager(this);
        nfcManager.setCallback(null, createNdefMessageCallback, onNdefPushCompleteCallback);
    }

    private boolean isBinding = false;

    @Override
    protected void onResume() {
        LogUtil.put(this,"onResume",LogUtil.WARN);
        super.onResume();
        try {
            nfcManager.verifyNFC();
            if (isBinding) {
                nfcManager.startBind();
            } else {
                nfcManager.stopBind();
            }
        } catch (NFCManager.NFCNotSupported nfcNotSupported) {
            nfcNotSupported.printStackTrace();
        } catch (NFCManager.NFCNotEnabled nfcNotEnabled) {
            nfcNotEnabled.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        LogUtil.put(this,"onPause",LogUtil.WARN);
        super.onPause();
    }

    private NfcAdapter.CreateNdefMessageCallback createNdefMessageCallback = new NfcAdapter.CreateNdefMessageCallback() {
        @Override
        public NdefMessage createNdefMessage(NfcEvent event) {
            if (bindingOne == null) {
                bindingOne = initNewFollower();
            }
            return nfcManager.createTextMessage(bindingOne);
        }
    };

    private Follower initNewFollower() {
        Follower follower = new Follower(gk, Encryption.getKillKey(), 12, followers.size() + 1, followersSize, 1, 2, 0);
        if (follower.getLength() > 2048) {
            return initNewFollower();
        } else {
            return follower;
        }
    }

    private int followersSize = 10;

    private NfcAdapter.OnNdefPushCompleteCallback onNdefPushCompleteCallback = new NfcAdapter.OnNdefPushCompleteCallback() {
        @Override
        public void onNdefPushComplete(NfcEvent event) {
            followers.add(bindingOne);
            refreshView.sendEmptyMessage(0);
            bindingOne = null;
            if (followers.size() >= followersSize) {
                stopBind();
            }
        }
    };

    private void startBind() {
        isBinding = true;
        nfcManager.startBind();
        recyclerView.setVisibility(View.VISIBLE);
        adapter = new BindNFCAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
    }

    private Handler refreshView = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            refreshView();
        }
    };

    private void refreshView() {
        adapter.refresh(followers);
    }

    private void stopBind() {
        isBinding = false;
        nfcManager.stopBind();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Encryption.NFC binary = nfcManager.readBinaryFromTag(intent);
        Toast.makeText(this, binary != null ? "接收到的数据：" + binary.getTerminalId() : "解析失败", Toast.LENGTH_SHORT).show();
    }
}
